<template>
    <div class="goods-list-container">
        <!-- 搜索区域 -->
        <el-form inline class="search-form">
            <el-form-item label="商品名称">
                <el-input v-model="searchParams.name" placeholder="请输入商品名称" clearable
                    @clear="fetchGoodsData"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="fetchGoodsData">搜索</el-button>
            </el-form-item>
            <el-form-item>
                <el-button type="success" @click="handleAdd">新增商品</el-button>
            </el-form-item>
        </el-form>

        <!-- 商品列表表格 -->
        <el-table :data="filteredGoodsList" border style="width: 100%" v-loading="loading">
            <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
            <el-table-column prop="name" label="商品名称" width="200" align="center"></el-table-column>
            <el-table-column prop="price" label="价格" width="120" align="center">
                <template slot-scope="scope">
                    {{ scope.row.price.toFixed(2) }} 积分
                </template>
            </el-table-column>
            <el-table-column prop="stock" label="库存" width="100" align="center"></el-table-column>
            <el-table-column prop="sold" label="已售" width="100" align="center"></el-table-column>
            <el-table-column prop="visited" label="访问量" width="100" align="center"></el-table-column>
            <el-table-column prop="description" label="商品描述" width="200" align="center">
                <template slot-scope="scope">
                    <el-tooltip class="item" effect="dark" :content="scope.row.description" placement="top-start">
                        <div class="description-preview">{{ scope.row.description }}</div>
                    </el-tooltip>
                </template>
            </el-table-column>
            <el-table-column prop="images" label="商品图片" width="200" align="center">
                <template slot-scope="scope">
                    <div v-for="(image, index) in scope.row.imagesArray" :key="index">
                        <img :src="image" alt="商品图片" style="width: 100px; height: auto; margin: 5px 0;" />
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="180" align="center"></el-table-column>
            <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button size="mini" type="text" class="delete-btn"
                        @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页区域 -->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
            :total="total"></el-pagination>

        <!-- 新增商品信息的对话框 -->
        <el-dialog title="新增商品信息" :visible.sync="addDialogVisible" width="50%">
            <el-form :model="addForm" label-width="120px" ref="addForm" :rules="addFormRules">
                <el-form-item label="商品名称" prop="name">
                    <el-input v-model="addForm.name"></el-input>
                </el-form-item>
                <el-form-item label="价格" prop="price">
                    <el-input-number v-model="addForm.price" :min="0" :step="0.01"
                        controls-position="right"></el-input-number>
                </el-form-item>
                <el-form-item label="库存" prop="stock">
                    <el-input-number v-model="addForm.stock" :min="0" controls-position="right"></el-input-number>
                </el-form-item>
                <el-form-item label="商品描述" prop="description">
                    <el-input type="textarea" v-model="addForm.description" :rows="4"></el-input>
                </el-form-item>
                <el-form-item label="上传图片" prop="file">
                    <el-upload class="upload-demo" action="http://localhost:10010/admin/common/upload"
                        :headers="{ token: user.token }" :on-success="handleUploadSuccess" :on-error="handleUploadError"
                        :before-upload="beforeUpload" :file-list="fileList" list-type="picture-card" :limit="1"
                        :on-exceed="handleExceed" :on-remove="handleRemove">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitAdd">确定</el-button>
            </span>
        </el-dialog>

        <!-- 编辑商品信息的对话框 -->
        <el-dialog title="编辑商品信息" :visible.sync="editDialogVisible" width="50%">
            <el-form :model="editForm" label-width="120px" ref="editForm" :rules="editFormRules">
                <el-form-item label="商品名称" prop="name">
                    <el-input v-model="editForm.name"></el-input>
                </el-form-item>
                <el-form-item label="价格" prop="price">
                    <el-input-number v-model="editForm.price" :min="0" :step="0.01"
                        controls-position="right"></el-input-number>
                </el-form-item>
                <el-form-item label="库存" prop="stock">
                    <el-input-number v-model="editForm.stock" :min="0" controls-position="right"></el-input-number>
                </el-form-item>
                <el-form-item label="商品描述" prop="description">
                    <el-input type="textarea" v-model="editForm.description" :rows="4"></el-input>
                </el-form-item>
                <el-form-item label="上传图片" prop="images">
                    <el-upload class="upload-demo" action="http://localhost:10010/admin/common/upload"
                        :headers="{ token: user.token }" :on-success="handleEditUploadSuccess"
                        :on-error="handleUploadError" :before-upload="beforeUpload" :file-list="editFileList"
                        list-type="picture-card" :limit="5" :on-exceed="handleExceed" :on-remove="handleEditRemove">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitEdit">确定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import request from '@/utils/request';
export default {
    data() {
        return {
            user: JSON.parse(localStorage.getItem('user') || '{}'),
            searchParams: {
                name: "",
                page: 1,
                pageSize: 10,
            },
            goodsList: [],
            total: 0,
            currentPage: 1,
            pageSize: 10,
            loading: false,
            addDialogVisible: false,
            editDialogVisible: false,
            addForm: {
                name: "",
                price: 0,
                stock: 0,
                description: "",
                images: [],
            },
            editForm: {
                id: null,
                name: "",
                price: 0,
                stock: 0,
                description: "",
                images: [],
            },
            addFormRules: {
                name: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
                price: [{ required: true, message: "请输入价格", trigger: "blur" }],
                stock: [{ required: true, message: "请输入库存", trigger: "blur" }],
                description: [
                    { required: true, message: "请输入商品描述", trigger: "blur" },
                ],
                images: [{ required: true, message: "请上传图片", trigger: "change" }],
            },
            editFormRules: {
                name: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
                price: [{ required: true, message: "请输入价格", trigger: "blur" }],
                stock: [{ required: true, message: "请输入库存", trigger: "blur" }],
                description: [
                    { required: true, message: "请输入商品描述", trigger: "blur" },
                ],
            },
            fileList: [],
            editFileList: [],
        };
    },
    computed: {
        // 过滤掉 delFlag 为 1 的数据
        filteredGoodsList() {
            return this.goodsList.map((item) => ({
                ...item,
                imagesArray: item.images ? item.images.split(",") : [],
            }));
        },
    },
    created() {
        this.fetchGoodsData();
    },
    methods: {
        // 获取商品数据
        fetchGoodsData() {
            this.loading = true;
            this.searchParams.page = this.currentPage;
            this.searchParams.pageSize = this.pageSize;

            request
                .get("/admin/goods/pageSearch", { params: this.searchParams })
                .then((response) => {
                    if (response && response.code === 1) {
                        this.goodsList = response.data.records || [];
                        this.total = response.data.total || 0;
                    } else {
                        this.$message.error("获取商品数据失败：" + response.message);
                    }
                })
                .catch((error) => {
                    console.error("获取商品数据失败：", error);
                    this.$message.error("获取商品数据失败：" + error.message);
                })
                .finally(() => {
                    this.loading = false;
                });
        },
        // 每页显示记录数改变时的处理
        handleSizeChange(newSize) {
            this.pageSize = newSize;
            this.fetchGoodsData(); // 重新获取数据
        },
        // 当前页码改变时的处理
        handleCurrentChange(newPage) {
            this.currentPage = newPage;
            this.fetchGoodsData(); // 重新获取数据
        },

        // 新增商品
        handleAdd() {
            this.addForm = {
                name: "",
                price: 0,
                stock: 0,
                description: "",
                images: [],
            };
            this.fileList = [];
            this.addDialogVisible = true;
        },
        // 提交新增
        submitAdd() {
            this.$refs.addForm.validate((valid) => {
                if (valid) {
                    const formData = {
                        name: this.addForm.name,
                        price: this.addForm.price,
                        stock: this.addForm.stock,
                        description: this.addForm.description,
                        images: this.addForm.images,
                    };

                    request
                        .post("/admin/goods/create", formData)
                        .then((response) => {
                            if (response && response.code === 1) {
                                this.$message.success("商品新增成功");
                                this.addDialogVisible = false;
                                this.fetchGoodsData(); // 刷新列表
                            } else {
                                this.$message.error("商品新增失败：" + data.message);
                            }
                        })
                        .catch((error) => {
                            console.error("商品新增失败：", error);
                            this.$message.error("商品新增失败：" + error.message);
                        });
                } else {
                    this.$message.error("表单验证失败，请检查输入");
                }
            });
        },
        // 文件上传成功
        handleUploadSuccess(response, file) {
            if (response && response.code === 1) {
                console.log(response.data)
                this.addForm.images.push(response.data); // 获取上传后的图片路径
                this.addForm.file = file; // 保存文件对象
                this.$message.success("图片上传成功");
                console.log(this.addForm)
            } else {
                this.$message.error("图片上传失败：" + response.message);
            }
        },
        // 文件上传失败
        handleUploadError(err, file) {
            this.$message.error("图片上传失败：" + err.message);
        },
        // 文件上传前的校验
        beforeUpload(file) {
            const isImage = file.type.startsWith("image/");
            if (!isImage) {
                this.$message.error("只能上传图片文件");
                return false;
            }
            return true;
        },
        // 文件超出限制
        handleExceed() {
            this.$message.warning("最多只能上传5张图片");
        },
        // 文件移除
        handleRemove(file, fileList) {
            console.log(file.response.data)
            const index = this.addForm.images.indexOf(file.response.data);
            console.log(index)
            if (index !== -1) {
                this.addForm.images.splice(index, 1);
            }
        },
        // 编辑商品
        handleEdit(row) {
            this.editForm = { ...row };
            this.editForm.images = row.images ? row.images.split(",") : [];
            this.editFileList = this.editForm.images.map((url) => ({ url }));
            this.editDialogVisible = true;
        },
        // 提交编辑
        submitEdit() {
            this.$refs.editForm.validate((valid) => {
                if (valid) {
                    const formData = {
                        id: this.editForm.id,
                        name: this.editForm.name,
                        price: this.editForm.price,
                        stock: this.editForm.stock,
                        description: this.editForm.description,
                        images: this.editForm.images.join(","),
                    };

                    request
                        .put("/admin/goods/update", formData)
                        .then((response) => {
                            if (response && response.code === 1) {
                                this.$message.success("商品更新成功");
                                this.editDialogVisible = false;
                                this.fetchGoodsData(); // 刷新列表
                            } else {
                                this.$message.error("商品更新失败：" + data.message);
                            }
                        })
                        .catch((error) => {
                            console.error("商品更新失败：", error);
                            this.$message.error("商品更新失败：" + error.message);
                        });
                } else {
                    this.$message.error("表单验证失败，请检查输入");
                }
            });
        },
        // 编辑时文件上传成功
        handleEditUploadSuccess(response, file) {
            if (response && response.code === 1) {
                this.editForm.images.push(response.data); // 将上传后的图片路径添加到数组
                this.editForm.file = file; // 保存文件对象
                this.$message.success("图片上传成功");
            } else {
                this.$message.error("图片上传失败：" + response.message);
            }
        },
        // 编辑时文件移除
        handleEditRemove(file, fileList) {
            const index = this.editForm.images.indexOf(file.response.data);
            if (index !== -1) {
                this.editForm.images.splice(index, 1);
            }
        },
        // 删除商品
        handleDelete(row) {
            this.$confirm("此操作将永久删除该商品, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    request
                        .delete("/admin/goods/delete", { params: { id: row.id } })
                        .then((response) => {
                            const data = response.data;
                            if (response && response.code === 1) {
                                this.$message.success("商品删除成功");
                                this.fetchGoodsData(); // 刷新列表
                            } else {
                                this.$message.error("商品删除失败：" + data.message);
                            }
                        })
                        .catch((error) => {
                            console.error("商品删除失败：", error);
                            this.$message.error("商品删除失败：" + error.message);
                        });
                })
                .catch(() => {
                    this.$message.info("已取消删除");
                });
        },
    },
};
</script>

<style scoped>
.goods-list-container {
    padding: 20px;
}

.search-form {
    margin-bottom: 20px;
}

.delete-btn {
    color: #f56c6c;
}

.description-preview {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    width: 180px;
}
</style>